package com.yh.correct.controller;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.yh.common.utils.IDUtils;
import com.yh.correct.model.CorrectedPerson;
import com.yh.correct.model.GroupJudicial;
import com.yh.correct.model.Page;
import com.yh.correct.model.Personnel;
import com.yh.correct.model.ResultData;
import com.yh.correct.service.IPersonnelService;
/**
 * 工作管理模块的工作人员 控制层
 * @author Administrator
 */
@RestController
@RequestMapping("/personnel")
public class PersonnelController {
	
	private static Logger logger = LogManager.getLogger(PersonnelController.class);
	
	@Autowired
	private IPersonnelService personnelService;
	
	@Value("${nginxPhotoPath}") /*comcn155 改为nginx路径*/
	private  String dir;
	
	/**
	 * 添加工作人员
	 * @param personnel
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping("/add")
	public ResultData addPersonnel(@Valid Personnel personnel,MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException{ 
		//上传文件的名字
		String oldName=file.getOriginalFilename();
		if(!"".equals(oldName)){
			//生成文件名字
			String newName=IDUtils.genImageName()+oldName.substring(oldName.lastIndexOf("."));
			//上传文件
			file.transferTo(new File(dir,newName));
			personnel.setPhoto(newName);
		}
		logger.info("增加工作人员"+personnel);
		int i=personnelService.addPersonnel(personnel);
		ResultData rd=new ResultData();
		if(i>0){
			rd.setCode(0);
			rd.setMessage("增加成功！");
		}else{
			rd.setCode(-1);
			rd.setMessage("增加失败！");
		}
		return rd;
	}
	
	/**
	 * 删除工作人员
	 * @param personnel
	 * @return
	 */
	@RequestMapping("/del")
	public ResultData delPersonnel(Personnel personnel){ 
		String oldPhoto=(String) personnelService.getPersonnel(personnel).get("photo");
		int i=personnelService.delPersonnel(personnel);
		if(oldPhoto!=null){
			File f=new File(dir,oldPhoto);
			if(f.exists()){
				f.delete();
			}
		}
		ResultData rd=new ResultData();
		if(i>0){
			rd.setCode(0);
			rd.setMessage("删除成功！");
		}else{
			rd.setCode(-1);
			rd.setMessage("删除失败！");
		}
		return rd;
	}
	
	/**
	 * 修改工作人员
	 * @param personnel
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping("/update")
	public ResultData updatePersonnel(@Valid Personnel personnel,MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException{ 
		String oldPhoto=null;
		if(!"".equals(file.getOriginalFilename())){
			oldPhoto=(String) personnelService.getPersonnel(personnel).get("photo");
			//上传文件的名字
			String oldName=file.getOriginalFilename();
			//生成文件名字
			String newName=IDUtils.genImageName()+oldName.substring(oldName.lastIndexOf("."));
			//上传文件
			file.transferTo(new File(dir,newName));
			personnel.setPhoto(newName);
		}
		logger.info("修改工作人员"+personnel);
		int i=personnelService.updatePersonnel(personnel);
		if(oldPhoto!=null){
			File f=new File(dir,oldPhoto);
			if(f.exists()){
				f.delete();
			}
		}
		ResultData rd=new ResultData();
		if(i>0){
			rd.setCode(0);
			rd.setMessage("修改成功！");
		}else{
			rd.setCode(-1);
			rd.setMessage("修改失败！");
		}
		return rd;
	}
	
	/**
	 * 根据id查询工作人员
	 * @param personnel
	 * @return
	 */
	@RequestMapping("/get")
	public ModelAndView getPersonnel(Personnel personnel){ 
		logger.info("查询工作人员"+personnel);
		Map<String,Object> pson=personnelService.getPersonnel(personnel);
		return new ModelAndView("work-manage/personnel_edit",pson);
	}
	
	/**
	 * 根据id查询工作人员及司法所名称
	 * @param personnel
	 * @return
	 */
	@RequestMapping("/get2")
	public ResultData getPersonnel2(Personnel personnel){ 
		logger.info("查询工作人员"+personnel);
		Map<String,Object> pson=personnelService.getPersonnel2(personnel);
		List<Object> list=new ArrayList<Object>();
		list.add(pson);
		ResultData rd=new ResultData();
		rd.setCode(0);
		rd.setMessage("查询成功！");
		rd.setData(list);
		return rd;
	}
	
	/**
	 * 模糊查询工作人员
	 * @param pageSize
	 * @param pageNum
	 * @param personnel
	 * @return
	 */
	@RequestMapping("/querylike")
	public ResultData queryLikePersonnels(Integer pageSize,Integer pageNum,Personnel personnel,Integer cid){ 
		CorrectedPerson cp = null;
		if(cid!=null){
			cp=new CorrectedPerson();
			cp.setId(cid);
		}
		logger.info("工作人员查询条件"+personnel+cp);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pageSize", pageSize);
		map.put("pageNum", pageNum);
		map.put("personnel",personnel);
		map.put("cp",cp);
		Page page=personnelService.queryLikePersonnels(map);
		List<Object> list=new ArrayList<Object>();
		list.add(page);
		ResultData rd=new ResultData();
		rd.setCode(0);
		rd.setMessage("查询成功！");
		rd.setData(list);
		return rd;
	}
	
	/**
	 * 导出工作人员
	 * @param personnel
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/export")
	public void exportPersonnels(Personnel personnel,HttpServletResponse response) throws IOException{ 
		logger.info("导出匹配的工作人员"+personnel);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("personnel",personnel);
		Workbook wb=personnelService.exportPersonnels(map);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");  
        String excelName = "工作人员";  
        response.setHeader("Content-Disposition","attachment; filename="+new String(excelName.getBytes("utf-8"), "ISO8859-1" )+".xls");  
		wb.write(response.getOutputStream());
	}
	/**
	 * 返回页面通用方法
	 * @param page
	 * @return
	 */
	@RequestMapping("/page")
	public ModelAndView page(String page){
		return new ModelAndView(page);
	}
	
	/**
	 * 根据工作人员id和矫正人员名字查询其所在矫正单位的所有匹配的矫正人员
	 * @param personnel
	 * @return
	 */
	@RequestMapping("/getCP")
	public ResultData getCP(Integer id,String name){
		logger.info("根据工作人员id和矫正人员名字查询其所在矫正单位的所有匹配的矫正人员"+id+name);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("id", id);
		map.put("name", name);
		List<Object> list=personnelService.getCP(map);
		ResultData rd=new ResultData();
		rd.setCode(0);
		rd.setMessage("查询成功！");
		rd.setData(list);
		return rd;
	}
	
	/**
	 * 查询工作人员所监督的对象或根据cid得到矫正对象
	 * @param personnel
	 * @return
	 */
	@RequestMapping("/getPcp")
	public ResultData getPcp(Integer id,Integer cid){
		logger.info("查询工作人员所监督的对象"+id+cid);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("id",id);
		map.put("cid",cid);
		List<Object> list=personnelService.getPcp(map);
		ResultData rd=new ResultData();
		rd.setCode(0);
		rd.setMessage("查询成功！");
		rd.setData(list);
		return rd;
	}
	
	/**
	 * 更新帮教小组（矫正对象与监督人员）
	 */
	@RequestMapping("/updateGroupOfPson")
	public ResultData updateGroupOfPson(String pid,@RequestParam(value="cList[]",required=false)List<Object> cList){
		logger.info("更新帮教小组（矫正对象与监督人员）"+pid+cList);
		List<GroupJudicial> list=new ArrayList<GroupJudicial>();
		if(cList!=null){
			for(Object n : cList){
				GroupJudicial groupJudicial=new GroupJudicial();
				groupJudicial.setDid(Integer.parseInt(pid));
				groupJudicial.setCid(Integer.parseInt(n.toString()));
				list.add(groupJudicial);
			}
		}
		personnelService.updateGroupOfPson(pid,list);
		ResultData rd=new ResultData();
		rd.setCode(0);
		rd.setMessage("更新成功！");
		return rd;
	}
}
